function C=eyelink2_quad_plot
% to check for error trials

clc
clear
%cd C:\_bcoe\EDF_Data\2003-12-12
files = dir('*C.mat'); % find all files with the eye extention
files.name;
if length(files)==0
    disp(' ');
    disp('there are no *C.mat files in this folder:')
    cd
    return
end
redraw=1;

sac_view_align=0;
file=1;
while file<=length(files)
    load(files(file).name)
    if ~isfield(C,'quad')
        C.quad((C.ang_ecc(:,1)== 45&C.anti==0)|(C.ang_ecc(:,1)==225&C.anti==1))=1;
        C.quad((C.ang_ecc(:,1)==135&C.anti==0)|(C.ang_ecc(:,1)==315&C.anti==1))=2;
        C.quad((C.ang_ecc(:,1)==225&C.anti==0)|(C.ang_ecc(:,1)== 45&C.anti==1))=3;
        C.quad((C.ang_ecc(:,1)==315&C.anti==0)|(C.ang_ecc(:,1)==135&C.anti==1))=4;
    end
    c=C.colors;
    if ~isfield(C,'error')
        C.error=zeros(size(C.quad));
    end
    sac_quad=1;
    plot_which=0;
    while sac_quad<5
        if redraw
            fig(1);clf;
            set(gcf,'name',files(file).name,'NumberTitle','off');
            
            h_position_plot=subplot('Position',[0.0571429 0.540476 0.919643 0.433333]);cla;tickout;hold on;axis ij
            h_eyetrace_plot=subplot('Position',[0.6518 0.0476 0.3321 0.4190]);cla;hold on;tickout;axis square; axis([-30.5 30.5 -30.5 30.5]);axis off
            h_saccade_view=subplot('Position',[0.0553571 0.052381 0.573214 0.407143]);cla;hold on;tickout;
            which_trials=find(C.quad==sac_quad);
            if ~plot_which
                plot_which=which_trials;
                plot_which(C.error(plot_which)>0)=[];
            end
            
            for tr_num=which_trials
                if C.anti(tr_num)
                    cuecolor=c.ANTI;
                else
                    cuecolor=c.PRO;
                end
                range1=C.e_start(tr_num):C.e_end(tr_num);
                range2=range1(C.blink(range1)>5)-min(range1)+1;
                t_align=C.fix_on(tr_num);
                time=C.time(range1)-t_align;
                eye_x=C.eye_x(range1)-C.x_adj(tr_num);
                eye_y=C.eye_y(range1)-C.y_adj(tr_num);
                which=find(tr_num==find(C.quad==sac_quad));
                %%%%%%%%%%%%%%
                subplot(h_position_plot)
                xlim([-10000 6000]);
                ylim([which-.5 which+.5]);
                hline(which,'k');
                vline([C.fix_on(tr_num) C.fix_off(tr_num)]-t_align,'k');
                vfill(C.cue_tgt_on(tr_num)-t_align, C.cue_tgt_off(tr_num)-t_align,cuecolor);
                vline(C.fix_off(tr_num)-t_align,'--k');
                if C.error(tr_num)
                    plot(time,-(eye_x/40)+which ,'.-','color',[0 .3 .4]);
                    plot(time,-(eye_y/40)+which ,'.-','color',[.4 0 .3]);
                    plot(time(range2),-(eye_x(range2)/40)+which ,'.','color',[0 .7 .7]);
                    plot(time(range2),-(eye_y(range2)/40)+which ,'.','color',[.7 0 .7]);
                    
                else
                    plot(time,-(eye_x/40)+which ,'.-c');
                    plot(time,-(eye_y/40)+which ,'.-m');
                    plot(time(range2),-(eye_x(range2)/40)+which ,'.','color',[0 .5 .5]);
                    plot(time(range2),-(eye_y(range2)/40)+which ,'.','color',[.5 0 .5]);
                end
                vline(C.sac_on(tr_num)-t_align,'-.g');
                hline(which+.5);
                %%%%%%%%%%%%%%
                subplot(h_eyetrace_plot);
                vline([-30 0 30],'c');
                hline([-30 0 30],'m');
                plot(0,0,'.k');
                plot(0,0,'ok');
                if sum(tr_num==plot_which) % plot only one or all saccades
                    [val loc1]=minfix((C.sac_on(tr_num)-t_align)-time );
                    [val loc2]=minfix((C.sac_off(tr_num)-t_align)-time );
                    plot(eye_x(loc1:loc1+60),eye_y(loc1:loc1+60),'-');
                    plot(eye_x(loc1:loc2),eye_y(loc1:loc2),'-','color',cuecolor);
                end
                [tgt_x tgt_y]=polar2cart(C.ang_ecc(tr_num,:));
                if C.peri(tr_num)
                    tgt(1)=plot(tgt_x,tgt_y,'.','color',cuecolor,'markersize',18);
                    t_title=('PERIPHERIAL CUE');
                else
                    tgt(1)=plot(tgt_x,tgt_y,'o','color',cuecolor);
                    t_title=('FOCAL CUE');
                end          
                title(t_title)
                %%%%%%%%%%%%%%
                subplot(h_saccade_view);
                            
                if sum(tr_num==plot_which) % plot only one or all saccades
                    ylim([-20 20]);
                    if sac_view_align & C.sac_on(tr_num)>0
                        [val loc3]=minfix((C.sac_on(tr_num)-t_align)-time );
                        val=time(loc3);
                        loc3=loc3-150;
                        view_sac_range=loc3:loc3+300;
                        vline(0);
                        title('saccade aligned')
                    else                
                        colors=[C.colors.PRO; C.colors.ANTI];
                        [val loc3]=minfix((C.cue_tgt_on(tr_num)-t_align)-time );
                        val=time(loc3);  
                        view_sac_range=loc3:loc3+300;
                        vline(C.srt(tr_num),colors(C.anti(tr_num)+1,:));
                        title('target aligned');
                    end
                    view_sac_range=loc3:loc3+100;
                    plot(time(view_sac_range)-val,eye_x(view_sac_range),'.-c');
                    plot(time(view_sac_range)-val,eye_y(view_sac_range),'.-m');
                    axis tight;ylim([-20 20]);
                end
                
            end % tr_num
            %%%%%%%%%%%%%%
            subplot(h_position_plot)  
            ylim([.5 which+.5]);box on
            set(gca,'yticklabel',which_trials)
            ylabel('Trial Number')
            
        end % if redraw 
        redraw=1; %automatically assume to redraw
        [x,y,button] = ginput(1);
        uistate = uiunsuspend(gcf);% a sub function i touched up to reenable the zoom (and other) functions; 
        switch button
            case 1, % left mouse button should select the saccade to be viewed 
                if (sum(x<get(gca,'xlim'))==1 & sum(y<get(gca,'ylim'))==1) % in current plot's lim's
                    switch gca % get current axis (built-in function) 
                        case h_position_plot % top xy position plot
                            if length(plot_which)==1 & plot_which==which_trials(round(y))
                                plot_which=which_trials; %plot all;
                                plot_which(C.error(plot_which)>0)=[];
                            else
                                plot_which=which_trials(round(y));%plot one
                            end
                        case h_eyetrace_plot, %lower right
                            %do nothing for now
                        case h_saccade_view %lower left
                            sac_view_align=abs(sac_view_align-1) % toggle sac v tgtoff align
                    end % switch which plot is current
                end % if in current plot's lim's                
            case 3 % right button
                if (sum(x<get(gca,'xlim'))==1 & sum(y<get(gca,'ylim'))==1) % in current plot's lim's
                    switch gca
                        case h_position_plot % top xy position plot
                            if C.error(which_trials(round(y)))==0
                                %C.error(which_trials(round(y)))=abs(C.error(which_trials(round(y)))-1);% toggle error
                                uimenufcn(gcf,'WindowCommandWindow');
                                clc;
                                disp('1) Premature/Double Saccade')
                                disp('2) No Saccade')
                                disp('3) Pro/anti switch')
                                a=input(['Error Type(1:3): ' ],'s');
                                while sum(a(1)~=['1' '2' '3'])==3
                                    clc;
                                    disp('1) Premature/Double Saccade')
                                    disp('2) No Saccade')
                                    disp('3) Pro/anti switch')
                                    a=input(['Error Type(1:3): ' ],'s');
                                end
                                C.error(which_trials(round(y)))=str2num(a(1));
                                fig(1);                                              
                                if length(plot_which)==1
                                    plot_which=which_trials; %plot all;
                                end
                                plot_which(C.error(plot_which)>0)=[];
                            else
                                C.error(which_trials(round(y)))=0;
                                plot_which=which_trials; %plot all;
                                plot_which(C.error(plot_which)>0)=[];                            
                            end
                        case h_eyetrace_plot, %lower right
                            %do nothing for now
                        case h_saccade_view %lower left
                            if length(plot_which)==1
                                C=refind_saccade_internal(C,plot_which);
                            end
                    end % switch which plot is current
                end % if in current plot's lim's                
            case 27, 
                %ESC button
                return;    
            case 66 % B for previous file
                sac_quad=100;
                file=max([1 file-1]);
            case 78 % N for next file
                sac_quad=100;
                file=file+1;    
            case 98, % b for back
                sac_quad=max([1 sac_quad-1]); 
                %       redraw=1;
                %       find_tgt_sac=1; 
                %       find_all_sac=1;
                plot_which=0;                
            case 103, % g for goto
                pause(0.01); % prevents flickering between windows
                clc; 
                %how do i send command window to the front? you'd thing input would do this automatically, right!
                uimenufcn(gcf,'WindowCommandWindow');
                clc;
                a=input(['\n\n\nGoTo Trial Number(1:' num2str(length(C.iti)) '): ' ],'s');
                fig(1);
                clc;
                if str2num(a) 
                    if str2num(a)>1 & str2num(a)<=length(C.iti)
                        tr_num=str2num(a); 
%                         redraw=1;
%                         find_tgt_sac=1; 
%                         find_all_sac=1;
                    end
                end
                plot_which=0;
            case 110, % n for next quad
                sac_quad=min([4 sac_quad+1]); 
                %       redraw=1;
                %       find_tgt_sac=1; 
                %       find_all_sac=1;
                plot_which=0;                
            case 112, 
                pause; % p for pause
            case 115 % s for save
                    save(lower([C.name 'C.mat']), 'C');
                    disp([' saved file: ' C.name 'C.mat']);
            otherwise % loop around but don't waist time redrawing
                %       find_tgt_sac=0;
                %       find_all_sac=0;
                redraw=0;
        end % switch button
    end %quad    
end% file
uimenufcn(gcf,'WindowCommandWindow');
clc;
disp(' ')
disp('FIN ')

return

function C=refind_saccade_internal(C,plot_which)

speed=C.speed(C.e_start(plot_which):C.e_end(plot_which));
time= C.time (C.e_start(plot_which):C.e_end(plot_which))-C.cue_tgt_on(plot_which);
eye_y=C.eye_y(C.e_start(plot_which):C.e_end(plot_which));
eye_x=C.eye_x(C.e_start(plot_which):C.e_end(plot_which));

            fix_noise=speed(speed<70); % most people use a fixed 50dps for saccade onset. here i remove all speeds over 70dps ... 
            sac_thres=max([20 mean(fix_noise)+(3*std(fix_noise))]); % and find the mean and 3std to create a variable threshold to compensate for different noise levels
            sac_pts=find(speed>(sac_thres)); % sometimes 50's too low and sometimes it's too high.
            sac_start_pos=(sac_pts(find(diff(sac_pts)>3)+1));
            sac_start_pos=[sac_pts(1); sac_start_pos];
            sac_end_pos=(sac_pts(find(diff(sac_pts)>3)));
            sac_end_pos=[sac_end_pos;sac_pts(end)];
            sac_start_times=time(sac_start_pos);
            sac_end_times=time(sac_end_pos);
            sac_dur=sac_end_times-sac_start_times; % make sure the 'saccades' last... 
            sac_start_pos(sac_dur<20)=[];% ignore if too short: <20 ms long
            sac_end_pos  (sac_dur<20)=[];% ignore if too short: <20 ms long
            
            sac_start_pos2=sac_start_pos; % for interactive section
            sac_end_pos2=sac_end_pos; % for interactive section
            sac_start_times2=time(sac_start_pos2);% for interactive section
            sac_end_times2=time(sac_end_pos2);% for interactive section

            clear sac_dur;
            sac_pts2=[];
            fast_enought=[];
            for i=1:length(sac_start_pos)
                sac_pts2=[sac_pts2 sac_start_pos(i):sac_end_pos(i)];
                fast_enought(i)=sum(speed(sac_start_pos(i):sac_end_pos(i))>80);
            end
            sac_start_pos(fast_enought==0)=[];% ignore if too slow: peak speed <=80 dps 
            sac_end_pos  (fast_enought==0)=[];% ignore if too slow: peak speed <=80 dps 
            
            sac_start_times=time(sac_start_pos);
            sac_end_times=time(sac_end_pos);
                %%%%%%%%%%%%%%%%%%%%%%%
    %find tgt sac
    bad_sac=0;
    bad_sac(length(sac_start_times),1)=0;%create a fuzzy boolean
    bad_sac(sac_start_times<100)=1; % ditch if too early
    bad_sac(sac_start_times>1800)=1; % ditch if too late
    %bad_sac(abs_speed(find_any(temp_eye_time,(round((sac_end_times-sac_start_times)/2)+sac_start_times)))<120)=1; % ditch if too slow <120 dps
    if length(sac_start_pos)>1 % if multiple saccades
        bad_sac([abs(eye_x(sac_start_pos))>5 & abs(eye_y(sac_start_pos))>5 ])=1; % if the saccade starts with the eye 6 deg (x&y) away from the fix )
    end
    tsac_on_time =min(sac_start_times(find(~bad_sac))); %find first saccade that matches guidlines
    tsac_off_time=min(sac_end_times  (find(~bad_sac))); %find first saccade that matches guidlines
    tsac_on_pos  =min(sac_start_pos  (find(~bad_sac))); %find first saccade that matches guidlines
    tsac_off_pos =min(sac_end_pos    (find(~bad_sac))); %find first saccade that matches guidlines
    tsac_range=tsac_on_pos:tsac_off_pos;


button=0;
while button<2
    fig(200);clf; 
    set(gcf,'Position',[2 342 1275 592])
    subplot(2,1,1);hold on; tickout
    plot(time,speed,'.-g')
    plot(time(sac_pts2),speed(sac_pts2),'.','color',[.8 .8 .8]);
    vline(sac_start_times2);
    if sac_start_times
        vline(sac_start_times,'k');
    end
    hline(sac_thres);        
    vline(sac_start_times(bad_sac==1));
    vline(tsac_on_time,'r');


    subplot(2,1,2);hold on; tickout
    plot(time,eye_x,'.-b');
    plot(time,eye_y,'.-r');
    vline(tsac_on_time,'g');
    drawnow
    
    [x,y,button] = ginput(1);
    uistate = uiunsuspend(gcf);% a sub function i touched up to reenable the zoom (and other) functions; 
    switch button
        case 1, % left mouse button should select the saccade to be viewed 
            if (sum(x<get(gca,'xlim'))==1 & sum(y<get(gca,'ylim'))==1) % in current plot's lim's
                new_sac=find(x>sac_start_times2 & x < sac_end_times2);
                if new_sac
                    tsac_on_time=sac_start_times2(new_sac);
                    tsac_off_time=sac_end_times2(new_sac);
                else
                    tsac_on_time=[];
                    tsac_off_time=[];
                end                
            end
        case 112, 
            pause; % p for pause
            button=0;  % dont leave just yet
            
    end
    
end

if tsac_on_time
    C.srt(plot_which)=tsac_on_time;
    C.sac_on(plot_which) =tsac_on_time+C.cue_tgt_on(plot_which);
    C.sac_off(plot_which)=tsac_off_time+C.cue_tgt_on(plot_which);
end

return;
